<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>sky图片模型</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../js/layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo">sky平台</div>
        <!-- 头部区域（可配合layui已有的水平导航） -->
        <ul class="layui-nav layui-layout-left">
            <li class="layui-nav-item"><a href="">控制台</a></li>
            <li class="layui-nav-item"><a href="">后台管理</a></li>
            <li class="layui-nav-item"><a href="">用户</a></li>
            <li class="layui-nav-item">
                <a href="javascript:;">其它系统</a>
                <dl class="layui-nav-child">
                    <dd><a href="">邮件管理</a></dd>
                    <dd><a href="">消息管理</a></dd>
                    <dd><a href="">授权管理</a></dd>
                </dl>
            </li>
        </ul>
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    <img src="http://t.cn/RCzsdCq" class="layui-nav-img">
                    sky
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="">基本资料</a></dd>
                    <dd><a href="">安全设置</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item"><a href="">退出</a></li>
        </ul>
    </div>

    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree" lay-filter="test">
                <li class="layui-nav-item layui-nav-itemed">
                    <a class="" href="javascript:;">商品分类</a>
                </li>
                <li class="layui-nav-item">
                    <a href="javascript:;">解决方案</a>
                    <dl class="layui-nav-child">
                        <dd><a href="javascript:;">列表一</a></dd>
                        <dd><a href="javascript:;">列表二</a></dd>
                        <dd><a href="">超链接</a></dd>
                    </dl>
                </li>
                <li class="layui-nav-item"><a href="">云市场</a></li>
                <li class="layui-nav-item"><a href="">追溯市场</a></li>
            </ul>
        </div>
    </div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <table class="layui-hide" id="image"></table>

        <form class="layui-form" lay-filter="imageForm" action="image/saveOrUpdateImage" id="imageForm" style="display: none" method="post" enctype="multipart/form-data">
            <br/>
            <br/>
            <div class="layui-form-item">
                <label class="layui-form-label">分类名称</label>
                <div class="layui-input-block">
                    <input type="hidden" style="width: 50%" id="id" name="id" class="layui-input">
                    <input type="hidden" style="width: 50%" id="images" name="images" value="" class="layui-input">
                    <input type="text" style="width: 50%" name="typeName" required lay-verify="required"
                           placeholder="请输入分类名称..." autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">品种编码</label>
                <div class="layui-input-block">
                    <input type="text" style="width: 50%" name="code" required lay-verify="required"
                           placeholder="请输入品种编码..." autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">品种名称</label>
                <div class="layui-input-block">
                    <input type="text" style="width: 50%" name="name" required lay-verify="required"
                           placeholder="请输入品种名称..." autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">上传图片</label>
                <div class="mark_button" id="files">
                    <button type="button" class="layui-btn layui-btn-normal" id="upload">选择文件</button>
                </div>
                <div class="layui-upload ">
                    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                        预览图（双击即可删除图片）：
                        <div class="layui-upload-list" id="imgs">
                        </div>
                    </blockquote>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block" style="margin-left: 400px;">
                    <button class="layui-btn" lay-submit="" lay-filter="imageFilter">立即提交</button>
                </div>
            </div>
        </form>
    </div>

    <div class="layui-footer">
        <!-- 底部固定区域 -->
        个人作品，邮箱：damowang0322@outlook.com
    </div>
</div>
<script src="../js/layui/layui.js" charset="utf-8"></script>
<script src="../js/jquery/jquery-3.3.1.min.js" charset="utf-8"></script>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" onclick="openForm()">新增</button>
    </div>
</script>

<script type="text/html" id="bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    layui.use(['element', 'upload', 'form', 'table'], function () {
        var $ = layui.jquery
            , element = layui.element
            , upload = layui.upload
            , form = layui.form
            , table = layui.table;

        table.render({
            elem: '#image'
            , toolbar: '#toolbar'
            , url: 'image/selectImage'
            , limit: 17
            , limits: [17, 30, 50, 100]
            , cols: [
                [
                    {field: 'id', width: 400, title: 'ID', sort: true}
                    ,{field: 'typeName', width: 400, title: '分类名称', sort: true}
                    , {field: 'code', width: 400, title: '品种编码'}
                    , {field: 'name', width: 400, title: '品种名称'}
                    , {field: 'images', width: 400, title: '图片', hide: true}
                    , {fixed: 'right', title: '操作', toolbar: '#bar', width: 150}
                ]
            ]
            , page: true
        });

        // 监听行工具事件
        table.on('tool', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('确定要删除吗？', function (index) {
                    $.ajax({
                        url: 'image/deleteImage',
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            _method: "DELETE",
                            'id': data.id
                        },
                        success: function () {
                            layer.msg('删除成功！', {icon: 6});
                        },
                        error: function () {
                            layer.alert('删除失败！', {icon: 5});
                        }
                    });
                    obj.del();
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                var index = openForm();
                layer.title('修改商品分类', index);
                form.val("imageForm", {
                    "id": data.id,
                    "typeName": data.typeName,
                    "code": data.code,
                    "name": data.name,
                    "images": data.images
                });
                if (null != data.images && undefined != data.images && '' != data.images) {
                    var imageList = data.images.split(",");
                    for (var i = 0; i < imageList.length; i++) {
                        if (null != imageList[i] && undefined != imageList[i] && '' != imageList[i]) {
                            $('#imgs').append("<img src=" + imageList[i] + " alt='图片暂不可查看！' ondblclick='deleteImg(this)' class='layui-upload-img' style='width: 85px; height: 100px'>");
                        }
                    }
                }
            }
        });

        // 多图片上传
        upload.render({
            elem: '#upload'
            , url: 'image/upload'
            , auto: true // 选择文件后不自动上传
            , multiple: true
            , data: {
                code: function(){
                    return $('#code').val();
                }
            }
            // , choose: function (obj) {
            //     // 预读本地文件，不支持ie8
            //     obj.preview(function (index, file, result) {
            //         $('#imgs').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img" style="width: 85px; height: 100px">')
            //     });
            // }
            , done: function (res) {
                //上传完毕
                $('#imgs').append("<img src=" + res.data + " alt='图片暂不可查看！' ondblclick='deleteImg(this)' class='layui-upload-img' style='width: 85px; height: 100px'>");
                if (null == $('#images').val() || undefined == $('#images').val() || '' == $('#images').val()) {
                    $('#images').val(res.data);
                } else {
                    $('#images').val($('#images').val() + "," + res.data);
                }
            }
            ,error: function(index, upload){
                layer.alert('请选择商品后，重新上传！', {icon: 5});
            }
        });

        // 提交
        form.on('submit(imageFilter)', function(data){
            $.ajax({
                url: 'image/saveOrUpdateImage',
                dataType: 'json',
                data: data.field,
                type: 'POST',
                success: function (data) {
                    layer.msg('保存成功！', {icon: 6});
                }
                ,error: function(xhr){
                    if (xhr.status == 400) {
                        layer.alert('分类名称已存在或没有上传图片！', {icon: 5});
                        // 删除文件
                        var inputList = $("#files").find("input");
                        for (var i = 0; i < inputList.length; i++) {
                            inputList[i].remove();
                        }
                        var imgList = $("#imgs").find("img");
                        for (var i = 0; i < imgList.length; i++) {
                            imgList[i].remove();
                        }
                    } else {
                        layer.alert('保存失败！', {icon: 5});
                    }
                }
            });
            table.reload("image");
            $("#imageForm")[0].reset();
            layer.closeAll(); // 它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算的
            table.reload("image");
            return false;
        });
    });

    // 弹层
    function openForm() {
        var index = layer.open({
            // layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            type: 1,
            title: "保存商品分类",
            area: ['50%', '50%'],
            shadeClose: false,
            shade: 0,
            content: $("#imageForm")
        });
        $("#imageForm")[0].reset();
        $('#id').val('');
        $('#images').val('');
        var inputList = $("#files").find("input");
        for (var i = 0; i < inputList.length; i++) {
            inputList[i].remove();
        }
        var imgList = $("#imgs").find("img");
        for (var i = 0; i < imgList.length; i++) {
            imgList[i].remove();
        }
        return index;
    }

    function deleteImg(thisimg) {
        // 删除图片
        thisimg.remove();
        if (null != $('#images').val() || undefined != $('#images').val() || '' != $('#images').val()) {
            var images = $('#images').val();
            var newImg = images.replace(thisimg.src, '');
            $('#images').val(newImg);
        }
        $.ajax({
            url: 'image/deleteImg',
            type: 'POST',
            dataType: 'json',
            data: {
                _method: "DELETE",
                'imgUrl': thisimg.src
            },
            success: function () {
                layer.msg('删除成功！', {icon: 6});
            },
            error: function () {
                layer.alert('删除失败！', {icon: 5});
            }
        })
    }

</script>

</body>
</html>
